#!/usr/bin/perl -w

#check parameters
if(@ARGV < 4)
{
	die("usage: command input1 input2 output cutoff\n");
}

# check interval, overlap ratio
open IN1, $ARGV[0] 
	or die "no input file1!";
open IN2, $ARGV[1]
	or die "no input file2!";
open OUT, ">$ARGV[2]"
	or die "no ouput file!";


# print usage -- optional

# 1
$intervs = ();
$tot = 0;
#$tot_line = 0;
$chr = ();
while(<IN1>)
{
	#$tot_line++;

	if(/(chr\w*)\t(\d*)\t(\d*)/)
	{
		$tot++;
		#print; exit; #
		$chr->{$1} += 1;
		#print $chr->{$1}; exit; ##
		
		$intervs->{$1}->{$chr->{$1} - 1}->{"start"} = $2 + 0; # '- 1'
		$intervs->{$1}->{$chr->{$1} - 1}->{"end"} = $3 + 0;
	}
	else
	{
		print $_; exit;
	}
}
#print $tot, '/', $tot_line; exit;


# 2
#$cutoff = .5;
$cutoff = $ARGV[3]; ##
$overlap = 0;
$common = 0;
while(<IN2>)
{
	if(/(chr.)\t(\d*)\t(\d*)/)
	{
		for($i = 0; $i < $chr->{$1}; $i++)
		{
			$overlap = check_interv($intervs->{$1}->{$i}->{"start"}, 
				$intervs->{$1}->{$i}->{"end"}, $2 + 0, $3 + 0);

			#print "overlap=$overlap\n"; exit; #

			if($overlap >= $cutoff)
			{
				#print "overlap=$overlap, $1, $2, $3\n"; exit; #
				$common++;
			}
		}
	}
}
print "common=$common, ($common / $tot)\n"; #
print OUT "common=$common, ($common / $tot)\n"; #

# return overlap percentage
sub check_interv
{
	# $x1 < $y1, $x2 < $y2
	my ($x1, $y1, $x2, $y2) = @_;
	my $dist = $y1 - $x1;
	
	if($x2 < $x1)
	{
		if(($y2 > $x1) && ($y2 < $y1))
		{
			return ($y2 - $x1) / $dist;
		}
		if($y2 > $y1)
		{
			return 1;
		}
	}
	else
	{
		if(($y2 > $x1) && ($y2 < $y1))
		{
			return ($y2 - $x2) / $dist;
		}
		if($y2 > $y1)
		{
			return ($y1 - $x2) / $dist;
		}
	}

	return 0;
}

